package com.freedy.concurrent.javaThread.twoStageTerminationMode;

import lombok.extern.slf4j.Slf4j;

/**
 * 两阶段终止模式
 * @author Freedy
 * @date 2021/4/20 19:07
 */
public class Test {
    public static void main(String[] args) throws InterruptedException {
        TwoStageTermination termination = new TwoStageTermination();
        termination.start();
        Thread.sleep(3500);
        termination.stop();
    }
}

@Slf4j
class TwoStageTermination {
    private Thread monitor;

    //启动监控线程
    public void start(){
        monitor=new Thread(()->{
            while (true){
                Thread current = Thread.currentThread();
                if (current.isInterrupted()){
                    //释放资源
                    log.debug("释放资源");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    //your code hear...
                    log.debug("执行监控记录");
                } catch (InterruptedException e) {
                    //重新设置打断标记
                    current.interrupt();
                    e.printStackTrace();
                }
            }
        });
        monitor.start();
    }

    //停止监控线程
    public void stop(){
        monitor.interrupt();
    }

}

